from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import viewsets
from rest_framework.response import Response

from shopping import serializers
from shopping import models
from shopping.serializers import ShoppingSerializer
from rest_framework.pagination import PageNumberPagination
class shopPage(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'
# Create your views here.
class ShoppingView(viewsets.ModelViewSet):
    queryset = models.shopping.objects.all()
    serializer_class = ShoppingSerializer
    pagination_class = shopPage
    def list(self, request, *args, **kwargs):
        data=self.queryset
        name=self.request.query_params.get('name')
        query=Q()
        s1=data.filter(query).all()
        se=self.request.query_params.get('page')
        if se:
            page=self.paginate_queryset(s1)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(s1, many=True)
        return Response(serializer.data)
    def update(self, request, *args, **kwargs):
            self.serializer_class = serializers.ShoppingSerializer
            info=self.queryset.get(pk=kwargs.get('pk'))
            ser=self.serializer_class(instance=info,data=request.data)
            if ser.is_valid():
                ser.save()
                return Response(ser.data, status=201)
            else:
                return Response(ser.errors, status=400)

    def retrieve(self, request, *args, **kwargs):
        # 重新指定序列化类
        self.serializer_class = serializers.ShoppingSerializer
        # 拿到我们要修改的那条数据
        info = self.queryset.get(pk=kwargs.get('pk'))
        ser = self.serializer_class(instance=info)
        return Response(ser.data)
